import { adminAreadDataGet } from '@/services/BaseLayout';
import { getCompanyID, getPosIDs, getUserDepID, getUserID, requestFunCompon } from '@/utils';
import { useCallback, useMemo } from 'react';
import { useRequest } from 'umi';
import { IUserTableService } from '../type';

// 获取用户列表数据
const userTableService = () => {
  const userTableRequest = useRequest(
    (opt: IUserTableService) => {
      let url = '/userController/dataGrid';
      let methodType = 'POST';
      return requestFunCompon(methodType, url, { ...opt });
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
    },
  );

  const reloadRightTable = useCallback((otherRequest: IUserTableService | any) => {
    const request: IUserTableService | any = {
      ...otherRequest,
    };
    userTableRequest?.run({
      ...request,
    });
  }, []);

  const userTableData = userTableRequest.data;

  const userTableLoading = userTableRequest.loading;

  return {
    reloadRightTable,
    userTableData,
    userTableLoading,
    refreshManageTable: userTableRequest?.refresh,
  };
};

// 获取详情
const getUserRowByID = (bodyParams: any) => {
  const userRowObj = useRequest(
    () => {
      let reqUrl = `/userController/getUserByID/${bodyParams?.id}`;
      return requestFunCompon('GET', reqUrl);
    },
    {
      manual: bodyParams && bodyParams?.id ? false : true, //页面初始请求为true
      onSuccess: (res) => {
        if (res && res?.msgFlag) {
          // message.success(res?.msg)
        }
      },
    },
  );

  // 处理数据
  let userDetail = useMemo(() => {
    return userRowObj?.data?.obj;
  }, [userRowObj.data]);

  return {
    userDetail: userDetail,
    userInfoLoading: userRowObj.loading,
    userInfofresh: userRowObj.run,
  };
};

// 获取省市县行政区域
const getAreadData = (params: any, curRes: any) => {
  const areadList = useRequest(() => {
    if (curRes['/commonController/getAreaNum']) {
      return adminAreadDataGet(params);
    } else {
      return [];
    }
  });

  return {
    areadList,
  };
};

// 开启关闭 用户状态
const switchUserIsOpen = (bodyPayload: any) => {
  let reqUrl = `/userController/modifyState`;
  let methodType = `PUT`;
  if (reqUrl && methodType) {
    return requestFunCompon(methodType, reqUrl, {
      modifyerID: getUserID(),
      modifyPositionID: getPosIDs(),
      modifyDepartmentID: getUserDepID(),
      modifyCompanyID: getCompanyID(),
      ...bodyPayload,
    });
  }
};

// 开启关闭 用户状态
const resetPwdUser = (bodyPayload: any) => {
  let reqUrl = `/userController/resetPwd`;
  let methodType = `PUT`;
  if (reqUrl && methodType) {
    return requestFunCompon(methodType, reqUrl, {
      modifyerID: getUserID(),
      modifyPositionID: getPosIDs(),
      modifyDepartmentID: getUserDepID(),
      modifyCompanyID: getCompanyID(),
      ...bodyPayload,
    });
  }
};

export {
  userTableService, //左侧树获取组织机构
  getUserRowByID, //获取详情
  getAreadData, //获取新增区域和数据字典
  switchUserIsOpen, //修改用户状态
  resetPwdUser, //重置用户密码
};
